#include "fram.h"

extern i2c_handle_type hi2c2;

void fram_init_param(void)
{
  // 恢复出厂设置
  printf("Set Default Settings\r\n");
  uint16_t boot_cnt = 0;
  fram_write_reg(FRAM_ADDR_BOOTCNT, 2, (uint8_t*)&boot_cnt);
  fram_write_reg(FRAM_ADDR_SETVELOCITY, 2, (uint8_t*)&boot_cnt);
}

void fram_init(void)
{
  i2c2_user_init();
  
  uint8_t is_inited;
  fram_read_reg(FRAM_ADDR_INITED, 1, (uint8_t*)&is_inited);
  if(is_inited == 0xFF)
  {
    is_inited = 0;
    fram_init_param();
    fram_write_reg(FRAM_ADDR_INITED, 1, (uint8_t*)&is_inited);
  }
}

void fram_read_reg(uint8_t addr, uint8_t cnt, uint8_t* val)
{
  i2c_memory_read_dma(&hi2c2, I2C_MEM_ADDR_WIDIH_8, FRAM_I2C_ADDR, addr, val, cnt, I2C_TIMEOUT);
  i2c_wait_end(&hi2c2, I2C_TIMEOUT);
}

void fram_write_reg(uint8_t addr, uint8_t cnt, uint8_t* val)
{
  i2c_memory_write_dma(&hi2c2, I2C_MEM_ADDR_WIDIH_8, FRAM_I2C_ADDR, addr, val, cnt, I2C_TIMEOUT);
  i2c_wait_end(&hi2c2, I2C_TIMEOUT);
}
